<template>
  <el-card>
    <template #header>
      <div>飞书登录</div>
    </template>
    <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
      <el-tab-pane label="飞书扫码" name="qr"></el-tab-pane>
      <el-tab-pane label="飞书授权" name="auth"></el-tab-pane>
    </el-tabs>
    <div v-show="activeName == 'qr'" id="login_container"></div>
    <el-button v-show="activeName == 'auth'" @click="openNewWin">
      授权登录
    </el-button>
  </el-card>
</template>

<script setup>
  import { onMounted } from "vue";

  var QRLoginObj;

  const activeName = ref("qr");

  const clientId = import.meta.env.VITE_NODE_FS_API_ID; //key

  // const redirectUri = window.location.origin + "/fslogin";
  const redirectUri = "http://10.10.41.132:15536/fslogin"; //测试地址【需要后台配置】
  const goto = `https://passport.feishu.cn/suite/passport/oauth/authorize?client_id=${clientId}&redirect_uri=${redirectUri}&response_type=code&state=STATE`;

  // 扫码登录初始化
  const initFsQr = () => {
    QRLoginObj = QRLogin({
      id: "login_container",
      goto: goto,
      width: "260",
      height: "260",
      style: "border:none;",
    });

    var handleMessage = function (event) {
      // 使用 matchOrigin 和 matchData 方法来判断 message 和来自的页面 url 是否合法
      if (
        QRLoginObj.matchOrigin(event.origin) &&
        QRLoginObj.matchData(event.data)
      ) {
        var loginTmpCode = event.data.tmp_code;
        // 在授权页面地址上拼接上参数 tmp_code，并跳转
        window.location.href = `${goto}&tmp_code=${loginTmpCode}`;
      }
    };
    if (typeof window.addEventListener != "undefined") {
      window.addEventListener("message", handleMessage, false);
    } else if (typeof window?.attachEvent != "undefined") {
      window?.attachEvent("onmessage", handleMessage);
    }
  };

  // 打开新窗口
  const openNewWin = (event) => {
    const appId = import.meta.env.VITE_NODE_FS_API_ID;
    const url = `https://applink.feishu.cn/client/web_app/open?appId=${appId}&mode=window`;

    // 打开新窗口全屏
    window.open(
      url,
      "_blank",
      "width=" +
        screen.width +
        ", height=" +
        screen.height +
        ", top=0, left=0, toolbar=no, menubar=no, location=no, status=no, help=no, center=yes, scrollbars=yes, resizable=yes, minmizebutton=yes, maxmizebutton=yes"
    );

    return;

    // 如果 需要在打开页后，再自动打开新窗口
    document.onreadystatechange = function (event) {
      if (document.readyState === "complete") {
        openNewWin(event);
      }
    };
  };

  // tabs
  const handleClick = (e) => {
    console.log(activeName.value);
  };

  onMounted(() => {
    initFsQr();
  });
</script>

<style lang="scss" scoped></style>
